import {HOT,SEARCH,SEARCH_SUGGEST} from '../api'

const defaultState = {
  hots:[],//热门搜索结果
  songs:[],//关键词搜索结果
  historyWords:localStorage.getItem("historyWords")?JSON.parse(localStorage.getItem("historyWords")):[],   //搜索过的关键词列表
  suggest:[],//搜索建议列表
}
/**
 * 
 * 搜索页 
 */
export default (state=defaultState,action)=>{
  switch(action.type){
    case 'INIT_HOTS':
      return {...state,hots:action.hots}
    case 'INIT_SONGS':
      return {...state,songs:action.songs}
    case 'ADD_KEY_WORDS':
      // 添加之前进行判断 如果在数组中找不到当前搜索的这一项 那么就把它添加到数组中去  否则 就返回原来的数组就行了
      let index =state.historyWords.indexOf(action.word);
      if(index===-1){
        let arr = [...state.historyWords,action.word]//创建一个新数组 将原来搜索过的词展开  拷贝原来数组的词到新数组中
        //存储到localStorage 中  并将数组转化为字符串
      localStorage.setItem('historyWords',JSON.stringify(arr))
     

      return {...state,historyWords:arr}
      }
      console.log(...state.historyWords)
      return state;
    case 'DEL_HISTORY':
      let index2=state.historyWords.indexOf(action.word)
      //不要改动原仓库 创建新的数组 从数组中删除 然后进行覆盖
      let arr2 =[...state.historyWords]
      arr2.splice(index2,1)
      localStorage.setItem('historyWords',JSON.stringify(arr2))
      return {...state,historyWords:arr2}
    case 'DEL_ALL_HISTORY':
      //清空所有历史记录
      localStorage.removeItem("historyWords")
      return {...state,historyWords:[]}
      //搜索建议
    case 'LOAD_SUGGEST':
      return {...state,suggest:action.suggest}
    default:
      return state;
  }
}

//加载热门搜索
export const loadHots=() =>(dispatch)=>{
  fetch(HOT).then(response=>response.json()).then(result=>{
    console.log(result.result.hots)//所需数据数组
    dispatch({
      type:'INIT_HOTS',
      hots:result.result.hots
    })
  })
}

//搜索关键字   搜索的内容作为参数传进去
export const search=(text)=>(dispatch)=>{
  fetch(SEARCH + text).then(response=>response.json()).then(result=>{
    console.log(result)
    dispatch({
      type:"INIT_SONGS",
      songs:result.result.songs
    })
  })
}

//历史记录
export const addHistoryWords=(word)=>(dispatch)=>{
  dispatch({
    type:"ADD_KEY_WORDS",
    word
  })
}

//删除每一条历史记录
export const delHistory =(word)=>(dispatch)=>{
  dispatch({
    type:'DEL_HISTORY',
    word
  })

}

//清空所有历史记录
export const delAllHistory =() =>(dispatch)=>{
  dispatch({
    type: 'DEL_ALL_HISTORY'
  })
}

//搜索建议
export const loadSuggest =(word)=>async (dispatch)=>{
  let data = await fetch(SEARCH_SUGGEST+word);
  let jsonData = await data.json()
  dispatch({
    type:'LOAD_SUGGEST',
    suggest:jsonData.result.allMatch
  })
 
}


